package com.itheima.Test;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.List;

public class Test001 {
    public static void main(String[] args) throws Exception {
        /*
        1. 请将dom4j包导入到项目中。
	    2. 使用dom4j读取1.1的books.xml文件，解析每条数据，并打印
         */
        SAXReader reader = new SAXReader();
        Document document = reader.read("Day22codes\\Books.xml");
        //获取根元素;
        Element root = document.getRootElement();
        //elements()     			: 获取当前元素的子元素
        List<Element> list = root.elements();
        //遍历集合
        Object a = null;
        PrintStream ps = new PrintStream("Day22codes\\bbb.txt");
        for (Element element : list) {
            String bookName = element.elementText("BookName");
            String publisher = element.elementText("Publisher");
            String date = element.elementText("Date");
            String price = element.elementText("price");
            a = "书名:" + bookName + "  出版社为:" + publisher + "  出版日期:" + date + "  售价为:" + price;
            System.setOut(ps);
            System.out.println(a);
        }
        FileInputStream fis = new FileInputStream("Day22codes\\bbb.txt");
        FileOutputStream fos = new FileOutputStream("Day22codes\\aaa.txt");
        //获取通道;
        FileChannel c = fis.getChannel();
        FileChannel c1 = fos.getChannel();
        //创建buffer缓冲区;
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        //读取数据;
        while (c.read(buffer) != -1) {
            //切记要切换;使用buffer
            buffer.flip();
            c1.write(buffer);
            buffer.clear();
        }
        ServerSocket ss = new ServerSocket(8888);
        //接收浏览器请求;
        Socket s = ss.accept();
        //获取网络输入流;
        InputStream is = s.getInputStream();
        //调用读取一行字符串的方法
        //readLine()
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String s1 = br.readLine();
        //截取
        String[] s2 = s1.split(" ");
        String name = s2[1];
        //获取输出流;
        BufferedOutputStream os = new BufferedOutputStream(s.getOutputStream());
        os.write("HTTP/1.1 200 OK\r\nContent-Type:text/html;charset=UTF-8\r\n\r\n".getBytes());
        os.write("书名:拜清清  出版社为:东池村  出版日期:1993-11-14  售价为:一毛钱 书名:张梓墨  出版社为:西安市未央区凤城十一路  出版日期:2019-06-13  售价为:无价之宝".getBytes());
        //关流;
        fis.close();
        fos.close();
        c.close();
        c1.close();
        is.close();
        br.close();
        os.close();


    }
}
